package com.sam;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sam.utils.Utils;

public class Login extends ActionSupport {
	private static final long serialVersionUID = -8707803393680010201L;
	private String userId;
	private String password;
	private String url;

	public void validate() {
		if (getUserId() != null && getUserId().length() == 0) {
			addFieldError("userId", "Usuario requerido!");
		}
		if (getPassword() != null && getPassword().length() == 0) {
			addFieldError("password", getText("password requerida!"));
		}
	}

	public String authenticate() throws Exception {
		boolean googleLogin = Boolean.parseBoolean(Utils
				.getProperty("googleLogin"));
		if (googleLogin) {
			return googleLogin();
		} else {
			return ejecutarlogin();
		}
	}

	public String execute() {
		boolean googleLogin = Boolean.parseBoolean(Utils
				.getProperty("googleLogin"));
		if (googleLogin) {
			return googleLogin();
		} else {
			return ejecutarlogin();
		}
	}

	private String googleLogin() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserService userService = UserServiceFactory.getUserService();
		HttpServletRequest request = ServletActionContext.getRequest();
		String thisURL = request.getRequestURI();
		if (request.getUserPrincipal() != null) {
			session.put("usuario", userService.getCurrentUser().getEmail());
			if (userService.isUserAdmin()) {
				return "ADMIN";
			}
			return "loggin";
		} else {
			setUrl(userService.createLoginURL(thisURL));
			return "notLoggin";
		}
	}

	private String ejecutarlogin() {

		/*
		 * try { setUp(); } catch (Exception e) { e.printStackTrace(); }
		 */
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("afiliadoValido", null);
		if (userId == null
				|| ("call2".equals(userId) && "1234".equals(password))) {
			addActionError(getText("Usuario o password incoracto!"));
			return ERROR;

		} else {
			session.put("usuario", userId);
			if (userId.equalsIgnoreCase("alejandrocabrera@mycrazymula.com.ar")) {
				return "ADMIN";
			} else {

				return SUCCESS;
			}
		}
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

}
